package com.bsy.videostation.viewmodel

import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bsy.common.viewmodel.BaseViewModel
import com.bsy.framework.ext.data
import com.bsy.network.callback.BaseApiErrorCallBack
import com.bsy.videostation.manager.ApiManager
import com.bsy.videostation.model.HomeEntity
import com.bsy.videostation.model.VideoEntity
import com.bsy.videostation.model.res.AppSourceItem
import com.bsy.videostation.model.res.VideoCategoryItem
import com.bsy.videostation.model.res.VideoInfo
import com.bsy.videostation.ui.fragment.AllContainerFragment
import com.bsy.videostation.ui.fragment.CategoryContainerFragment
import com.bsy.videostation.ui.fragment.HomeContainerFragment
import com.bsy.videostation.ui.fragment.MyFragment
import com.dg.videostation.R
import com.google.gson.JsonParser
import com.google.gson.JsonSyntaxException
import kotlinx.coroutines.launch

/**
 * Created by Sincerity on 2024/5/21.
 * Copyright
 * 描述：
 */
class MainViewModel : BaseViewModel() {
    val tabIcons = intArrayOf(
        R.drawable.selector_home,
        R.drawable.selector_all,
        R.drawable.selector_category,
        R.drawable.selector_my
    )

    //首页所有的Fragment
    val fragments: MutableList<Fragment> = mutableListOf()

    //视频列表
    val videoList = MutableLiveData<MutableList<HomeEntity>>()

    //面板信息
    val panel = MutableLiveData<MutableList<VideoCategoryItem>>()

    //头
    val headerData = MutableLiveData<VideoEntity?>()

    //app信息
    val appData = MutableLiveData<MutableList<AppSourceItem>?>()

    //点击了历史记录后Fragment替换
    val historyEvent = MutableLiveData<Int>()

    //选中的分类id
    var categorySelectId: String? = null

    //分类
    val categoryEvent = MutableLiveData<Int>()

    //分类
    val allEvent = MutableLiveData<Int>()

    //Tab的点击事件
    val enableTabEvent = MutableLiveData<Boolean>()

    //恢复到首个为止
    val homeScrollToFirstPosition = MutableLiveData<Int>()

    //恢复到首个为止
    val categoryScrollToFirstPosition = MutableLiveData<Int>()

    //恢复到首个为止
    val allScrollToFirstPosition = MutableLiveData<Int>()


    init {
        fragments.add(HomeContainerFragment.newInstance())
        fragments.add(CategoryContainerFragment.newInstance())
        fragments.add(AllContainerFragment.newInstance())
        fragments.add(MyFragment.newInstance())
    }

    /**
     * 获取视频列表
     */
    fun getVideoListById(showLoading: (Boolean) -> Unit) {
        launchFlow(errorCall = BaseApiErrorCallBack(), requestCall = { ApiManager.api.getPanelInfo() }, showLoading = showLoading) {
            val tabList = it?.tabResultModels?.map { tabInfo ->
                VideoCategoryItem(id = tabInfo?.tag_id.data(), title = tabInfo?.tag_name_en.data(), desc = "Телесериал великолепен")
            }?.toMutableList() ?: mutableListOf()
            categorySelectId = tabList.firstOrNull()?.id.toString()
            panel.value = tabList
        }
    }

    /**
     * 获取首页的推荐数据
     */
    fun fetchAllVideos(homePanelInfo: MutableList<VideoCategoryItem>) {
        viewModelScope.launch {
            getHomeAllVideoData(homePanelInfo)
        }
    }

    /**
     * 获取首页的推荐数据
     */
    private suspend fun getHomeAllVideoData(homePanelInfo: MutableList<VideoCategoryItem>) {
        val requestList = homePanelInfo.map { panelInfo ->
            suspend { ApiManager.api.getVideoList(panelInfo.id.toString()) }
        }
        launchMultipleFlows(
            errorCall = BaseApiErrorCallBack(),
            requestCalls = requestList,
            showLoading = null,
            successBlock = {
                val homeEntityList = it.flatMap { videoInfo ->
                    buildVideoList(videoInfo)
                }
                videoList.value = buildAdapterData(homeEntityList,true)
            })

    }

    /**
     * 数据处理 构建一个首页可用的数据  VideoEntity
     * @param response VideoInfo? 原始数据
     * @return MutableList<VideoEntity> 重新整理后的数据
     */
    private fun buildVideoList(response: VideoInfo?): MutableList<VideoEntity> {
        if (response == null) return mutableListOf()
        val videos = mutableListOf<VideoEntity>()
        val appList = mutableMapOf<String, AppSourceItem>()
        //拿取封面
        response.panelReleases?.forEach {
            it.video_contents?.forEach { videoInfo ->
                val id = videoInfo.id.data()
                //    拿到视屏相关信息
                val video = videoInfo.block?.block_content_info
                //是否上架中
                if (video?.content_status == 1) {
                    var cover: String? = null
                    var isVertical: Boolean? = false
                    //封面信息
                    if (video.imgs?.allPoster != null && video.imgs.allPoster.isNotEmpty()) {
                        val coverInfo = video.imgs.allPoster[0]
                        //封面
                        cover = coverInfo?.url.data()
                        //封面是横屏还是竖屏
                        isVertical = coverInfo?.style.data() == "v"
                    }
                    //标题
                    val title = video.title.data()
                    val isShowTitle = video.show_title.data() == 0
                    //详情url
                    val detail = video.action.data()
                    var url: String? = null
                    if (detail.isNotEmpty()) {
                        try {
                            // 使用 Gson 的 JsonParser 解析 detail 字符串为 JsonObject
                            val obj = JsonParser.parseString(detail).asJsonObject
                            // 直接获取 obj 中的 "url" 属性
                            if (obj.has("url")) {
                                url = obj.get("url").asString
                            }
                        } catch (e: JsonSyntaxException) {
                            e.printStackTrace()
                        } catch (e: IllegalStateException) {
                            e.printStackTrace()
                        }
                    }
                    var appUrl: String? = null
                    var appName: String? = null
                    //来源图标
                    if (video.app_info != null) {
                        appUrl = video.app_info.app_url.data()
                        appName = video.app_info.supplier.data()
                        val appId = video.app_info.app_third_id.data()
                        if (appUrl.isNotEmpty() && appName.isNotEmpty())
                            appList[appName] = (AppSourceItem(appId, appName, appUrl, id, url))
                    }
                    videos.add(
                        VideoEntity(
                            id,
                            cover,
                            isVertical.data(),
                            title,
                            url.data(),
                            isShowTitle,
                            appUrl,
                            appName
                        )
                    )
                }
            }
        }

        appData.value = appList.values.toMutableList()
        return videos

    }

    /**
     * 构建首页的数据
     * @param videos MutableList<VideoEntity>
     */
    fun buildAdapterData(videos: List<VideoEntity>, isRemoveHeader: Boolean): MutableList<HomeEntity> {
        val vList = videos.toMutableList()
        // 创建 homeEntity 列表
        val homeEntities: MutableList<HomeEntity> = mutableListOf()

        // 初始化索引
        var vIndex = 0
        // 拿出第一个元素作为 HeaderData
        if (isRemoveHeader)
            headerData.value = vList.removeFirstOrNull()
        // 循环直到 vList 或 hList 都被处理完
        while (vIndex < vList.size) {
            val homeEntity = HomeEntity()
            for (i in 0 until 5) {
                if (vIndex < vList.size) {
                    val entity = vList[vIndex]
                    entity.index = vIndex
                    homeEntity.vItem.add(entity)
                    vIndex++
                }
            }
            homeEntities.add(homeEntity)
        }
        return homeEntities
    }

}